import re
from django.contrib.auth.backends import ModelBackend
from .models import User


def get_user_by_account(account):
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if request is None:

            # 管理员验证
            if user.is_superuser and user.check_password(password):
                return user

        else:

            if user and user.check_password(password):
                return user
